<template>
	<div class="pagination">
		<button @click="prev" :disabled="PageNo == 1">上一页</button>
		<button v-show="startNumAndEndNum.start >= 3" @click="changePage">1</button>

		<button disabled v-show="startNumAndEndNum.start >= 3">···</button>

		<button v-for="item in num" :key="item" :class="{ active: item === PageNo }" @click="changePage">{{ item }}</button>

		<button disabled v-show="startNumAndEndNum.end <= totalPage - 2">···</button>
		<button v-show="startNumAndEndNum.end <= totalPage - 2" @click="changePage">{{ totalPage }}</button>
		<button @click="next" :disabled="PageNo == totalPage">下一页</button>

		<button style="margin-left: 30px" disabled>共 {{ total }} 条</button>
	</div>
</template>

<script>
export default {
	name: 'Pagination',
	props: ['pageNo', 'pageSize', 'total', 'continues'],
	data() {
		return {
			PageNo: this.pageNo
		};
	},
	computed: {
		// 总页数
		totalPage() {
			return Math.ceil(this.total / this.pageSize);
		},
		// 连续页码的起始数字与结束数字
		startNumAndEndNum() {
			// 定义两个变量存储起始值和结束值
			let start = 0,
				end = 0;
			// 不正常情况解决
			// 不正常【1】：总页数小于连续页码
			if (this.totalPage < this.continues) {
				start = 1;
				end = this.totalPage;
			} else {
				// 正常现象
				// Math.floor(this.continues / 2) 动态计算要减去的数字，如果连续页码为7则减3，5则减2
				// 起始数字
				start = this.pageNo - Math.floor(this.continues / 2);
				// 结束数字
				end = this.pageNo * 1 + Math.floor(this.continues / 2);

				// 不正常现象【2】：起始数字小于1，结束数字大于总页数
				if (start <= 1) {
					// 如果起始页减2还小于等于1的情况下，则起始页为1，结束页为连续页码
					start = 1;
					end = this.continues;
				} else if (end >= this.totalPage) {
					// 如果结束页加2大于总页数的情况下，则结束页为总页数，起始页为总页数-连续页码+1
					// 结束页为11的话，其实页应该为7
					end = this.totalPage;
					start = this.totalPage - this.continues + 1;
				}
			}
			return { start, end };
		},
		// 返回计算后的连续页码数组进行遍历
		num() {
			let endVal = this.startNumAndEndNum.end;
			let arr = [];
			for (let i = 1; i <= endVal; i++) {
				arr.push(i);
			}
			arr = arr.filter(item => {
				return item >= this.startNumAndEndNum.start;
			});

			return arr;
		}
	},
	methods: {
		// 上一页
		prev() {
			this.PageNo -= 1;
			this.$emit('getPageNo', this.PageNo);
		},
		// 下一页
		next() {
			this.PageNo += 1;
			this.$emit('getPageNo', this.PageNo);
		},
		// 直接点击某个页数
		changePage(e) {
			this.PageNo = Number(e.target.innerHTML);
			this.$emit('getPageNo', Number(e.target.innerHTML));
		}
	}
};
</script>

<style lang="less" scoped>
.pagination {
	text-align: center;
	button {
		margin: 0 5px;
		background-color: #f4f4f5;
		color: #606266;
		outline: none;
		border-radius: 2px;
		padding: 0 4px;
		vertical-align: top;
		display: inline-block;
		font-size: 13px;
		min-width: 35.5px;
		height: 28px;
		line-height: 28px;
		cursor: pointer;
		box-sizing: border-box;
		text-align: center;
		border: 0;

		&[disabled] {
			color: #c0c4cc;
			cursor: not-allowed;
		}

		&.active {
			cursor: not-allowed;
			background-color: #1abc9c;
			color: #fff;
		}
	}
}
</style>
